import axios from 'axios'
import store from '@/store'
import router from '@/router'

// 创建axios实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  // baseURL: 'http://ihrm-java.itheima.net', // 设置axios请求的基础的基础地址
  timeout: 5000 // 定义5秒超时
})

// 响应拦截器
service.interceptors.response.use(response => {
  if (response.data.success) {
    return response.data
  } else {
    return Promise.reject(new Error(response.data.message))
  }
},
async error => {
  if (error.response.data.code === 10002) {
    await store.dispatch('user/userLogOut')
    router.push('/login?return_url=' + this.route.path)
  }
  return Promise.reject(error) // 返回执行错误 让当前的执行链跳出成功 直接进入 catch
})

// 请求拦截器(加token)
service.interceptors.request.use(
  config => {
    const token = store.state.user.token
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

export default service
